<template>
  <div class="login">
    <div class="login-box">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名：" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="passWord">
          <el-input v-model="ruleForm.passWord"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { getLogin } from "@/api";
import { useRouter } from "vue-router";

export default defineComponent({
  components: {},
  setup() {
    const router = useRouter();
    const ruleFormRef = ref<any>();
    const ruleForm = reactive({
      userName: "",
      passWord: "",
    });
    const rules = reactive({
      userName: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "change",
        },
      ],
      passWord: [
        {
          required: true,
          message: "请输入密码",
          trigger: "change",
        },
      ],
    });
    const submitForm = async (ruleFormRef: any) => {
      if (!ruleFormRef) return;
      await ruleFormRef.validate((valid: any) => {
        if (valid) {
          getLogin(ruleForm).then((res) => {
            if (res == -1) ElMessage.error("用户不存在！");
            if (res == 1) ElMessage.error("密码错误！");
            if (res == 0) {
              router.push("/");
              localStorage.setItem("userName", ruleForm.userName);
              resetForm(ruleFormRef);
            }
          });
        } else {
          ElMessage.error("登录信息不能为空！");
          return false;
        }
      });
    };
    const resetForm = (ruleFormRef: any) => {
      if (!ruleFormRef) return;
      ruleFormRef.resetFields();
    };
    return {
      ruleFormRef,
      ruleForm,
      rules,
      submitForm,
      resetForm,
    };
  },
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  &-box {
    width: 40%;
    margin-top: 10%;
  }
}
</style>